//
//  BOCImageDownloader.m
//  BOCImageTools
//
//  Created by LeungChaos on 16/5/11.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "BOCImageDownloader.h"
#import "BOCImageDownloadTask.h"

@interface BOCImageDownloader ()

// 唯一的会话对象
@property (nonatomic, strong) NSURLSession *downSession;

// 保存失败的url
//@property (nonatomic, strong) NSMutableSet *failURLs;

//// 正在请求的url
//@property (nonatomic, strong) NSMutableSet *loadingURLs;

//@property (nonatomic, strong) NSMutableDictionary<NSString *,BOCImageDownloadTask *> *taskContainer;


@end

@implementation BOCImageDownloader


- (instancetype)init
{
    self = [super init];
    if (self) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        self.downSession = [NSURLSession sessionWithConfiguration:config];
        
//        self.failURLs = [NSMutableSet set];
        
//        self.loadingURLs = [NSMutableSet set];
    }
    return self;
}


- (BOCImageDownloadTask *)downImageWithURL:(NSURL *)url progress:(BOCProgressHandlerProgressBlock)progressBlock seccess:(BOCDownloadImageSeccessBlock)seccessBlock fail:(BOCDownloadImageFailErrorBlock)errorBlock
{
    BOCImageDownloadTask *task =
    [[BOCImageDownloadTask alloc]initWithUrl:url
                                    progress:progressBlock
                                     session:self.downSession
                                     seccess:^(UIImage *image, NSURLResponse *response) {
                                         // 下载成功后 url 从loadingURLs集合中移出
                                         if (seccessBlock) {
                                             seccessBlock(image, response);
                                         }
                                     }
                                        fail:^(NSError *error, NSURLResponse *response) {
                                            // 下载发生错误 url 从loadingURLs集合中移出，并添加到failURLs集合中

                                            if (errorBlock) {
                                                errorBlock(error,response);
                                            }
                                        }];

    return task;
}

@end
